<?php
error_reporting(E_ALL);
define('APP_PATH',realpath(dirname(__FILE__)));
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Mvc\Router;
function _p($val, $die = true)
{
     header("content-Type: text/html; charset=Utf-8");  
    $out  = "<pre style=\"background: #000; color: #ccc; font: 12px 'fixedsys'; text-align: left; width: 100%; padding: 5px\">\n";
    $out .= print_r($val, true);
    $out .= "</pre>\n";
    echo $out;
    if ($die) {
       exit();
    }

   
}
//_p(APP_PATH);
//define('APP_PATH', realpath('..'));
/*
 * 初始数据加载处理
 */
function _config(){
     $main_config = unserialize(file_get_contents(APP_PATH . "/data/config/config.php"));
     //_p($main_config);
     $reutrn_datas = array();
     $reutrn_datas['routes'] = array();
     $reutrn_datas['registerDirs'] = array();
     foreach ($main_config as $app => $v) {
         if($app == 'database'){//数据库配置
             $reutrn_datas['config']['database'] = $v;
         }else{
             $reutrn_datas['config'][$app] = array(
                'controllersDir' => APP_PATH . '/app/'.$app.'/controller/',
                'modelsDir'      => APP_PATH . '/app/'.$app.'/models/',
                'migrationsDir'  => APP_PATH . '/app/'.$app.'/migrations/',
                'viewsDir'       => APP_PATH . '/app/'.$app.'/views/',
                'pluginsDir'     => APP_PATH . '/app/'.$app.'/plugins/',
                'libraryDir'     => APP_PATH . '/app/'.$app.'/library/',
                'cacheDir'       => APP_PATH . '/data/cache/'.$app.'/',
                'baseUri'        => '/phalcon_store/',  
             );
             //ucwords($str)
             $reutrn_datas['registerNamespaces'][ucwords($app).'\Controllers'] = APP_PATH."/app/".$app."/controller/";
             $reutrn_datas['registerNamespaces'][ucwords($app).'\Models'] = APP_PATH."/app/".$app."/models/";  
             $registerDirs = array(
                 APP_PATH . '/app/'.$app.'/controller/',
                 APP_PATH . '/app/'.$app.'/models/',
             );
             $reutrn_datas['registerDirs'] = array_merge($reutrn_datas['registerDirs'],$registerDirs);
             //路由
             $reutrn_datas['routes'] = array_merge($reutrn_datas['routes'],$v['routes']);
         }

     }
     return $reutrn_datas;

}
try {

    /**
     * Read the configuration
     */
    global $_CONFIG;
    
    global $_CONFIG_DATAS;
    
    $_CONFIG_DATAS = _config();
    
    
    
     $_CONFIG = new \Phalcon\Config($_CONFIG_DATAS['config']);
     //_p($_CONFIG);
     $loader = new \Phalcon\Loader();
    //注册命名空间
    $loader->registerNamespaces($_CONFIG_DATAS['registerNamespaces'])->register();
    $loader->registerDirs($_CONFIG_DATAS['registerDirs'])->register();
    //_p($loader);

    /**
     * Read services
     */
    /**
     * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
     */
    $di = new FactoryDefault();

    /**
     * The URL component is used to generate all kind of urls in the application
     */
    $di->setShared('url', function () use ($_CONFIG) {
        $url = new UrlResolver();
        $url->setBaseUri($_CONFIG->b2c->baseUri);
        return $url;
    });

    /**
     * Setting up the view component
     */
    $di->setShared('view', function () use ($_CONFIG) {

        $view = new View();

        $view->setViewsDir($_CONFIG->b2c->viewsDir);

        $view->registerEngines(array(
            '.volt' => function ($view, $di) use ($_CONFIG) {

                $volt = new VoltEngine($view, $di);

                $volt->setOptions(array(
                    'compiledPath' => $_CONFIG->b2c->cacheDir,
                    'compiledSeparator' => '_'
                ));

                return $volt;
            },
            '.phtml' => 'Phalcon\Mvc\View\Engine\Php'
        ));

        return $view;
    });

    /**
     * Database connection is created based in the parameters defined in the configuration file
     */
    $di->setShared('db', function () use ($_CONFIG) {
        $dbConfig = $_CONFIG->database->toArray();
        $adapter = $dbConfig['adapter'];
        unset($dbConfig['adapter']);

        $class = 'Phalcon\Db\Adapter\Pdo\\' . $adapter;

        return new $class($dbConfig);
    });

    /**
     * If the configuration specify the use of metadata adapter use it or use memory otherwise
     */
    $di->setShared('modelsMetadata', function () {
        return new MetaDataAdapter();
    });

    /**
     * Register the session flash service with the Twitter Bootstrap classes
     */
    $di->set('flash', function () {
        return new Flash(array(
            'error'   => 'alert alert-danger',
            'success' => 'alert alert-success',
            'notice'  => 'alert alert-info',
            'warning' => 'alert alert-warning'
        ));
    });

    /**
     * Start the session the first time some component request the session service
     */
    $di->setShared('session', function () {
        $session = new SessionAdapter();
        $session->start();

        return $session;
    });
    //_p($di);
    /**
     * Add routing capabilities
     */
//            $di->set('router', function () {
//                require APP_PATH.'/config/routes.php';
//                return $router;
//            });

    
    $di->set('router', function () {
            $router = new Router();
            global $_CONFIG_DATAS;
            foreach ($_CONFIG_DATAS['routes'] as $k => $v) {
                $router->add($k,$v);
            }
            return $router;
    });
//_p($di);
    /**
     * Handle the request
     */
   //_p($di);
    $application = new \Phalcon\Mvc\Application($di);
    //_p($di);
//_p(  $application);
    echo $application->handle()->getContent();

} catch (\Exception $e) {
    echo $e->getMessage() . '<br>';
    echo '<pre>' . $e->getTraceAsString() . '</pre>';
}

